<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>交易记录</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#3B82F6',
            success: '#10B981',
            danger: '#EF4444',
            warning: '#F59E0B',
            neutral: '#6B7280'
          },
          fontFamily: {
            sans: ['Inter', 'system-ui', 'sans-serif']
          }
        }
      }
    }
  </script>

  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .transaction-row {
        @apply hover:bg-gray-50 transition-colors duration-150;
      }
      .status-badge {
        @apply px-2 py-1 rounded-full text-xs font-medium;
      }
    }
  </style>
</head>
<body class="bg-gray-50 font-sans text-gray-800 min-h-screen">
<!-- 顶部导航 -->
<header class="bg-white shadow-sm sticky top-0 z-10">
  <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
    <div class="flex justify-between items-center h-16">
      <div class="flex items-center space-x-2">
        <i class="fa fa-bank text-primary text-xl"></i>
        <span class="text-xl font-bold text-gray-800">交易记录</span>
      </div>
      <div class="flex items-center space-x-4">
        <button id="refreshButton" class="flex items-center px-4 py-2 bg-primary/10 text-primary rounded-md hover:bg-primary/20 transition-colors duration-200">
          <i class="fa fa-refresh mr-2"></i>刷新
        </button>
      </div>
    </div>
  </div>
</header>

<!-- 主内容区 -->
<main class="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
  <div class="bg-white rounded-xl shadow-md overflow-hidden">
    <!-- 标题和描述 -->
    <div class="px-6 py-5 border-b border-gray-200">
      <h2 class="text-xl font-semibold text-gray-900">我的交易记录</h2>
      <p class="text-sm text-gray-500 mt-1">显示最近的账户交易活动</p>
    </div>

    <!-- 用户信息 -->
    <div class="px-6 py-3 bg-gray-50 border-b border-gray-200">
      <div class="flex items-center">
        <i class="fa fa-user-circle-o text-primary mr-2"></i>
        <span class="text-sm text-gray-700">当前用户: <span id="currentUserId" class="font-medium">-</span></span>
      </div>
    </div>

    <!-- 状态提示区 -->
    <div id="loadingState" class="hidden p-12 text-center">
      <div class="inline-block animate-spin rounded-full h-12 w-12 border-4 border-primary/20 border-t-primary mb-4"></div>
      <p class="text-gray-500">正在加载交易记录...</p>
    </div>

    <div id="errorState" class="hidden p-12 text-center">
      <div class="inline-flex items-center justify-center w-12 h-12 rounded-full bg-red-100 mb-4">
        <i class="fa fa-exclamation-triangle text-red-500 text-xl"></i>
      </div>
      <h3 class="text-lg font-medium text-red-700 mb-2">加载失败</h3>
      <p id="errorMessage" class="text-gray-500 mb-4"></p>
      <button id="retryButton" class="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary/90 transition-colors duration-200">
        重试
      </button>
    </div>

    <div id="emptyState" class="hidden p-12 text-center">
      <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-gray-100 mb-4">
        <i class="fa fa-file-text-o text-gray-400 text-2xl"></i>
      </div>
      <h3 class="text-lg font-medium text-gray-900 mb-2">暂无交易记录</h3>
      <p class="text-gray-500 mb-6">完成交易后，记录将显示在此处</p>
      <a href="#" class="text-primary hover:text-primary/80 font-medium">
        <i class="fa fa-plus-circle mr-1"></i>发起交易
      </a>
    </div>

    <!-- 交易表格 -->
    <div id="contentState" class="hidden overflow-x-auto">
      <table class="min-w-full divide-y divide-gray-200">
        <thead class="bg-gray-50">
        <tr>
          <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">交易ID</th>
          <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">转出账户</th>
          <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">转入账户</th>
          <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">金额</th>
          <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">交易时间</th>
          <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
          <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">手续费</th>
        </tr>
        </thead>
        <tbody id="transactionTableBody" class="bg-white divide-y divide-gray-200">
        <!-- 交易记录将通过JS动态填充 -->
        </tbody>
      </table>
    </div>
  </div>
</main>
<!-- 底部管理栏 -->
<div class="footer mt-8 flex justify-center">
  <a href="UserHome.html"
     class="inline-flex items-center px-6 py-3 bg-primary text-white font-medium rounded-lg shadow hover:bg-primary/90 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary transition-all duration-200">
    <i class="fa fa-sign-out mr-2"></i>
    返回主页
  </a>
</div>

<!-- 页脚 -->
<footer class="bg-white border-t border-gray-200 mt-12">
  <div class="max-w-7xl mx-auto py-8 px-4 sm:px-6 lg:px-8">
    <div class="flex flex-col md:flex-row justify-between items-center">
      <div class="text-center md:text-left mb-4 md:mb-0">
        <p class="text-sm text-gray-500">© 2025 在线银行. 保留所有权利.</p>
      </div>
      <div class="flex space-x-6">
        <a href="#" class="text-gray-400 hover:text-gray-500 transition-colors duration-200">
          <i class="fa fa-question-circle"></i>
          <span class="ml-1 text-sm">帮助中心</span>
        </a>
        <a href="#" class="text-gray-400 hover:text-gray-500 transition-colors duration-200">
          <i class="fa fa-shield"></i>
          <span class="ml-1 text-sm">安全中心</span>
        </a>
      </div>
    </div>
  </div>
</footer>

<script>
  // 应用状态管理
  const appState = {
    userId: null,
    transactions: [],
    loading: false,
    error: null
  };

  // DOM 元素引用
  const elements = {
    currentUserId: document.getElementById('currentUserId'),
    transactionTableBody: document.getElementById('transactionTableBody'),
    loadingState: document.getElementById('loadingState'),
    errorState: document.getElementById('errorState'),
    errorMessage: document.getElementById('errorMessage'),
    emptyState: document.getElementById('emptyState'),
    contentState: document.getElementById('contentState'),
    refreshButton: document.getElementById('refreshButton'),
    retryButton: document.getElementById('retryButton')
  };

  // 直接显示后端返回的字符串（不做任何转换）
  function displayAsIs(value, fieldName = '字段') {
    if (value === null || value === undefined) {
      console.log(`字段 "${fieldName}" 为 ${value}，显示默认值`);
      return '<span class="text-gray-400">-</span>';
    }

    // 处理空字符串
    if (typeof value === 'string' && value.trim() === '') {
      return '<span class="text-gray-400">-</span>';
    }

    // 直接显示原始值
    return value;
  }

  // 格式化交易状态
  function formatStatus(status) {
    switch (status) {
      case '成功':
        return '<span class="status-badge bg-success/10 text-success">成功</span>';
      case '失败':
        return '<span class="status-badge bg-danger/10 text-danger">失败</span>';
      case '处理中':
        return '<span class="status-badge bg-warning/10 text-warning">处理中</span>';
      default:
        return `<span class="status-badge bg-neutral/10 text-neutral">${status || '未知'}</span>`;
    }
  }

  // 更新应用状态并渲染UI
  function updateAppState(newState) {
    Object.assign(appState, newState);

    // 显示/隐藏对应状态区域
    elements.loadingState.classList.toggle('hidden', !appState.loading);
    elements.errorState.classList.toggle('hidden', !appState.error);
    elements.emptyState.classList.toggle('hidden', appState.transactions.length > 0 || appState.loading || appState.error);
    elements.contentState.classList.toggle('hidden', appState.transactions.length === 0 || appState.loading || appState.error);

    // 更新用户ID显示
    elements.currentUserId.textContent = appState.userId || '-';

    // 渲染交易表格
    renderTransactionTable();
  }

  // 渲染交易表格
  function renderTransactionTable() {
    elements.transactionTableBody.innerHTML = '';

    appState.transactions.forEach(tx => {
      const row = document.createElement('tr');
      row.className = 'transaction-row';

      // 判断是收入还是支出
      const isExpense = tx.fromAccountId && tx.fromAccountId.toString() === appState.userId.toString();
      const amountClass = isExpense ? 'text-danger' : 'text-success';
      const amountSign = isExpense ? '-' : '+';

      row.innerHTML = `
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${displayAsIs(tx.transactionsId, '交易ID')}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${displayAsIs(tx.fromAccountId, '转出账户')}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${displayAsIs(tx.toAccountId, '转入账户')}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm ${amountClass}">
                        ${amountSign}${displayAsIs(tx.amount, '交易金额')}
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${displayAsIs(tx.transactionTime, '交易时间')}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm">${formatStatus(tx.transactionStatus)}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${displayAsIs(tx.feeAmount, '手续费')}</td>
                `;

      elements.transactionTableBody.appendChild(row);
    });
  }

  // 获取当前用户信息
  async function fetchCurrentUser() {
    updateAppState({ loading: true, error: null });

    try {
      const response = await fetch('/user/currentUser');

      if (!response.ok) {
        throw new Error('未登录或会话已过期');
      }

      const data = await response.json();

      if (data.code === 2000 && data.data) {
        updateAppState({ userId: data.data.userId });
        return data.data.userId;
      } else {
        throw new Error('无法获取用户信息，请重新登录');
      }
    } catch (error) {
      console.error("获取用户信息失败:", error);
      updateAppState({ error: error.message });
      setTimeout(() => {
        window.location.href = '/userInfo.html';
      }, 3000);
      return null;
    }
  }

  // 获取交易记录
  async function fetchTransactions(userId) {
    if (!userId) return;

    updateAppState({ loading: true, error: null });

    try {
      const response = await fetch(`/dealings/transactions?userId=${userId}`);

      if (!response.ok) {
        throw new Error(`HTTP错误 ${response.status}: ${response.statusText}`);
      }

      const result = await response.json();

      if (result.code === 2000) {
        const transactions = Array.isArray(result.data) ? result.data : [];

        // 调试：打印第一条交易记录的数据结构
        if (transactions.length > 0) {
          console.log('第一条交易记录数据结构:', transactions[0]);
        }

        updateAppState({ transactions, loading: false });
      } else {
        throw new Error(result.message || '获取交易记录失败');
      }
    } catch (error) {
      console.error('获取交易记录失败:', error);
      updateAppState({ error: error.message, loading: false });
    }
  }

  // 初始化应用
  async function initApp() {
    const userId = await fetchCurrentUser();
    if (userId) {
      await fetchTransactions(userId);
    }
  }

  // 事件监听器
  elements.refreshButton.addEventListener('click', () => fetchTransactions(appState.userId));
  elements.retryButton.addEventListener('click', () => fetchTransactions(appState.userId));

  // 页面加载完成后初始化应用
  document.addEventListener('DOMContentLoaded', initApp);
</script>
</body>
</html>